package org.budo.dubbo.protocol.http.api.impl;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.budo.dubbo.protocol.http.BudoDubboHttpProtocol;
import org.budo.dubbo.protocol.http.api.RegistryApi;
import org.budo.dubbo.protocol.http.util.BudoReflectionUtil;
import org.budo.support.lang.util.ReflectUtil;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.rpc.Exporter;

/**
 * @author lmw
 */
public class RegistryApiImpl implements RegistryApi {
    @Override
    public List<Map<String, Object>> lookup() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        Map<String, Exporter<?>> exporterMap = BudoDubboHttpProtocol.getInstance().getExporterMap();
        for (Entry<String, Exporter<?>> entry : exporterMap.entrySet()) {
            String interfaceName = entry.getKey();
            String matchedInterfaceName = BudoReflectionUtil.getMatchedInterfaceNameCached(interfaceName); // 已缓存

            Class classForName = ReflectUtil.classForName(matchedInterfaceName);
            Method[] methods = classForName.getMethods();
            List<String> methodNames = new ArrayList<String>();
            for (Method method : methods) {
                methodNames.add(method.getName());
            }

            Map stringObjectMap = CollectionUtils.toMap("type", classForName.getSimpleName(), //
                    "methods", methodNames);
            list.add(stringObjectMap);
        }

        return list;
    }
}